package supernova

import "gddgame.cc/galaxy/utils/orm"

type Migration struct {
	Path  string
	model *orm.Model

	*Engine
}

func NewMigration(dsn string, path string) (*Migration, error) {
	engine, err := NewEngineWithDsn(dsn)
	if err != nil {
		return nil, err
	}

	model := getModel(engine.executor)
	migration := &Migration{
		Path:   path,
		model:  model,
		Engine: engine,
	}

	return migration, nil
}

func (migration *Migration) init() {
	// 写入model表

}

func (migration *Migration) Create() {

}

func (migration *Migration) Sync(dns string, prefix string, includeRecords bool) error {
	engine, err := NewEngineWithDsn(dns)
	if err != nil {
		return err
	}

	source, err := migration.Engine.AnalysisDatabase(prefix)
	if err != nil {
		return err
	}
	desc, err := engine.AnalysisDatabase(prefix)
	if err != nil {
		return err
	}
	diffs := NewDiffSlice(source, desc)
	operations := diffs.Operation()
	if err := migration.Engine.ExecDatabase(operations, nil); err != nil {
		return err
	}
	if includeRecords {
		results := make([][][]interface{}, len(desc))
		for index, table := range desc {
			operations = []Operation{}
			operations = append(operations, AllRecords(table))
			result, err := engine.QueryDatabase(operations, nil)
			if err != nil {
				return err
			}
			results[index] = result[0].([][]interface{})
		}
		for index, table := range desc {
			operations = []Operation{}
			operations = append(operations, ClearRecords(table))
			items := results[index]
			if items == nil {
				continue
			}
			operations = append(operations, AddRecords(table, items))
			err := engine.ExecDatabase(operations, nil)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func (migration *Migration) Up() {

}

func (migration *Migration) Down() {

}
